
package com.shiku.utils.encrypt;


public class HEX {
    static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};


    public static String encode(byte[] data) {

        char[] result = new char[data.length * 2];

        int c = 0;

        for (byte b : data) {

            result[c++] = HEX_DIGITS[b >> 4 & 0xF];

            result[c++] = HEX_DIGITS[b & 0xF];

        }

        return new String(result);

    }


    public static byte[] decode(String hex) {

        if (hex == null) {
            throw new IllegalArgumentException("hex == null");
        }

        if (hex.length() % 2 != 0) {

            throw new IllegalArgumentException("Unexpected hex string: " + hex);

        }

        byte[] result = new byte[hex.length() / 2];

        for (int i = 0; i < result.length; i++) {

            int d1 = decodeHexDigit(hex.charAt(i * 2)) << 4;

            int d2 = decodeHexDigit(hex.charAt(i * 2 + 1));

            result[i] = (byte) (d1 + d2);

        }

        return result;

    }


    private static int decodeHexDigit(char c) {

        if (c >= '0' && c <= '9') {
            return c - 48;
        }

        if (c >= 'a' && c <= 'f') {
            return c - 97 + 10;
        }

        if (c >= 'A' && c <= 'F') {
            return c - 65 + 10;
        }

        throw new IllegalArgumentException("Unexpected hex digit: " + c);

    }

}


